package org.hyacinth.user.listener;

import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.hyacinth.common.constant.Constants;
import org.hyacinth.common.utils.JsonUtils;
import org.hyacinth.common.utils.MailUtils;
import org.hyacinth.user.dataobject.UserInfo;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class UserQueueListener {

    @Resource
    private MailUtils mailUtils;
//    @RabbitListener(queues = Constants.USER_QUEUE_NAME)
//    public void println(Message message, Channel channel) throws IOException {
//        long deliveryTag = message.getMessageProperties().getDeliveryTag();
//        try {
//            String body = new String(message.getBody());
//            log.info("收到用户信息: " + body);
//
//            channel.basicAck(deliveryTag, true);
//        } catch (Exception e) {
//            channel.basicNack(deliveryTag, true, true);
//        }
//    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = Constants.USER_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(name = Constants.USER_EXCHANGE_NAME, type = ExchangeTypes.FANOUT)
    ))
    public void println(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            String body = new String(message.getBody());
            log.info("收到用户信息: " + body);

            UserInfo userInfo = JsonUtils.parseJson(body, UserInfo.class);
            mailUtils.sendMail(userInfo.getEmail());
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            channel.basicNack(deliveryTag, true, true);
        }
    }
}
